package com.ruoyi.disease.service.impl;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.department.domain.Department;
import com.ruoyi.department.mapper.DepartmentMapper;
import com.ruoyi.departmentdisease.domain.DepartmentDisease;
import com.ruoyi.departmentdisease.domain.vo.DepartmentDiseaseVO;
import com.ruoyi.departmentdisease.mapper.DepartmentDiseaseMapper;
import com.ruoyi.userdisease.domain.UserDisease;
import com.ruoyi.userdisease.mapper.UserDiseaseMapper;
import com.ruoyi.wx.utils.PinyinUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.disease.mapper.DiseaseMapper;
import com.ruoyi.disease.domain.Disease;
import com.ruoyi.disease.service.IDiseaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【病种】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-02
 */
@Service
public class DiseaseServiceImpl implements IDiseaseService {
    @Autowired
    private DiseaseMapper diseaseMapper;

    @Autowired
    private DepartmentDiseaseMapper departmentDiseaseMapper;

    @Autowired
    private UserDiseaseMapper userDiseaseMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param diseaseId 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public DepartmentDiseaseVO selectDiseaseByDiseaseId(Long diseaseId) {
        Disease disease = diseaseMapper.selectDiseaseByDiseaseId(diseaseId);
        DepartmentDisease departmentDisease = departmentDiseaseMapper.selectDepartmentDiseaseByDiseaseId(diseaseId);
        DepartmentDiseaseVO departmentDiseaseVO = new DepartmentDiseaseVO();
        BeanUtils.copyProperties(disease, departmentDiseaseVO);
        departmentDiseaseVO.setDepartmentId(departmentDisease.getDepartmentId());
        return departmentDiseaseVO;
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param disease 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<DepartmentDiseaseVO> selectDiseaseList(Disease disease) {
        List<DepartmentDiseaseVO> departmentDiseaseVOS = new ArrayList<>();
        List<Disease> diseases = diseaseMapper.selectDiseaseList(disease);
        for (Disease disease1 : diseases) {
            DepartmentDiseaseVO departmentDiseaseVO = new DepartmentDiseaseVO();
            Long diseaseId = disease1.getDiseaseId();
            DepartmentDisease departmentDisease = departmentDiseaseMapper.selectDepartmentDiseaseByDiseaseId(diseaseId);
            BeanUtils.copyProperties(disease1, departmentDiseaseVO);
            departmentDiseaseVO.setDepartmentId(departmentDisease.getDepartmentId());
            Department department = departmentMapper.selectDepartmentByDepartmentId(departmentDisease.getDepartmentId());
            departmentDiseaseVO.setDepartmentName(department.getDepartmentType());
            departmentDiseaseVOS.add(departmentDiseaseVO);
        }
        return departmentDiseaseVOS;
    }
    @Override
    public int selectDiseaseList1(Disease disease) {
        return diseaseMapper.selectDiseases();
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param departmentDiseaseVO 【请填写功能名称】
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDisease(DepartmentDiseaseVO departmentDiseaseVO) {
        Disease disease = new Disease();
        BeanUtils.copyProperties(departmentDiseaseVO, disease);
        disease.setCreateTime(DateUtils.getNowDate());
        String firstPinyinChar = PinyinUtil.getFirstPinyinChar(disease.getIllnessName());
        disease.setSort(firstPinyinChar);
        diseaseMapper.insertDisease(disease);
        DepartmentDisease departmentDisease = new DepartmentDisease();
        departmentDisease.setDiseaseId(disease.getDiseaseId());
        departmentDisease.setDepartmentId(departmentDiseaseVO.getDepartmentId());
        return departmentDiseaseMapper.insertDepartmentDisease(departmentDisease);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param departmentDiseaseVO 【请填写功能名称】
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDisease(DepartmentDiseaseVO departmentDiseaseVO) {
        Disease disease = new Disease();
        BeanUtils.copyProperties(departmentDiseaseVO, disease);
        disease.setUpdateTime(DateUtils.getNowDate());
        diseaseMapper.updateDisease(disease);
        DepartmentDisease departmentDisease = new DepartmentDisease();
        departmentDisease.setDiseaseId(disease.getDiseaseId());
        departmentDisease.setDepartmentId(departmentDiseaseVO.getDepartmentId());
        return departmentDiseaseMapper.updateDepartmentDisease(departmentDisease);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param diseaseIds 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteDiseaseByDiseaseIds(Long[] diseaseIds) {
        diseaseMapper.deleteDiseaseByDiseaseIds(diseaseIds);
        userDiseaseMapper.deleteUserDiseaseByDiseaseIds(diseaseIds);
        return departmentDiseaseMapper.deleteDepartmentDiseaseByDiseaseIds(diseaseIds);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param diseaseId 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteDiseaseByDiseaseId(Long diseaseId) {
        diseaseMapper.deleteDiseaseByDiseaseId(diseaseId);
        return departmentDiseaseMapper.deleteDepartmentDiseaseByDiseaseId(diseaseId);
    }

    /**
     * 查询专家对应的病种
     *
     * @param userId
     * @return
     */
    @Override
    public List<Disease> selectUserDisease(String userId) {
        List<Disease> diseases = new ArrayList<>();
        UserDisease userDisease = new UserDisease();
        userDisease.setUserId(userId);
        List<UserDisease> userDiseases = userDiseaseMapper.selectUserDiseaseList(userDisease);
        for (UserDisease disease : userDiseases) {
            Disease disease1 = diseaseMapper.selectDiseaseByDiseaseId(disease.getDiseaseId());
            diseases.add(disease1);
        }
        return diseases;
    }

    @Override
    @Transactional
    public int deleteDiseaseAll() {
        diseaseMapper.deleteDiseaseAll();
        userDiseaseMapper.deleteUserDiseaseAll();
        return departmentDiseaseMapper.deleteDepartmentDiseaseAll();
    }


    /**
     * 上传病种
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public AjaxResult addFile(MultipartFile file) throws IOException {
        ExcelUtil<Disease> util = new ExcelUtil<>(Disease.class);
        List<Disease> diseaseList = util.importExcel(file.getInputStream());
        // 先对 diseaseList 中的 illnessName 和 departmentName 去前后空格
        diseaseList.forEach(disease -> {
            if (disease.getIllnessName() != null) {
                disease.setIllnessName(disease.getIllnessName().trim());
            }
            if (disease.getDepartmentName() != null) {
                disease.setDepartmentName(disease.getDepartmentName().trim());
            }
        });
        // ✅ 1. Excel 内部去重，按照 illnessName 去重（保留第一条）
        Map<String, Disease> uniqueExcelMap = diseaseList.stream()
                .filter(disease -> StringUtils.isNotBlank(disease.getIllnessName()))
                .collect(Collectors.toMap(
                        Disease::getIllnessName,
                        disease -> disease,
                        (existing, replacement) -> existing // 重复时保留第一条
                ));
        List<Disease> uniqueExcelList = new ArrayList<>(uniqueExcelMap.values());

        // ✅ 2. 查询数据库已有的疾病列表
        List<Disease> existingDiseases = diseaseMapper.selectDiseaseList(new Disease());

        // ✅ 3. 提取已有疾病名
        Set<String> existingNames = existingDiseases.stream()
                .map(Disease::getIllnessName)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());

        // ✅ 4. 过滤掉数据库中已存在的疾病
        List<Disease> newDiseases = uniqueExcelList.stream()
                .filter(disease -> !existingNames.contains(disease.getIllnessName()))
                .collect(Collectors.toList());

        // ✅ 5. 插入并绑定科室
        int successCount = 0;
        for (Disease disease : newDiseases) {
            // ⚠️ selectDepartmentByName 要确保返回唯一，否则改用 selectList + 模糊匹配
            Department department = departmentMapper.selectDepartmentByName(disease.getDepartmentName());
            String firstPinyinChar = PinyinUtil.getFirstPinyinChar(disease.getIllnessName());
            disease.setSort(firstPinyinChar);
            diseaseMapper.insertDisease(disease);

            DepartmentDisease departmentDisease = new DepartmentDisease();
            departmentDisease.setDepartmentId(department.getDepartmentId());
            departmentDisease.setDiseaseId(disease.getDiseaseId());
            departmentDiseaseMapper.insertDepartmentDisease(departmentDisease);

            successCount++;
        }

        return AjaxResult.success("导入成功，共导入 " + successCount + " 条新疾病数据");
    }

}
